package com.jyu.apts.controller;

import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jyu.apts.utils.AliyunOSSUtil;
import com.jyu.apts.utils.DateUtil;
import com.jyu.apts.utils.URLCache;

@RestController
public class AliyunOssController {
	
	Map<String,URLCache> urlCacheMap = new ConcurrentHashMap<String,URLCache>();
	
	private static final Logger LOG = LoggerFactory.getLogger(AliyunOssController.class);
	
	@Scheduled(cron = "59 0/5 * * * ?")
	public void clearURLCacheTimerWorker() throws ParseException {
		Date currentDate = new Date();
		LOG.info("clearURLCacheTimerWorker work : "+DateUtil.getYYYY_MM_DD_HH_MM_SS_Format().format(currentDate));
		urlCacheMap.forEach((objectName,urlCache)->{
			if(urlCache.expiration.before(currentDate)) {
				urlCacheMap.remove(objectName);
			}
		});
	}
	
	@RequestMapping("/oss/{objectName}")
	public void getOssObject(@PathVariable("objectName")String objectName,HttpServletResponse response) throws IOException{
		if(objectName == null || objectName.trim().length()==0) {
			return;
		}
		if(urlCacheMap.get(objectName) == null) {
			synchronized (AliyunOssController.class) {
				if(urlCacheMap.get(objectName) == null) {
					URLCache urlCache = AliyunOSSUtil.generateUrlCache(objectName);
					urlCacheMap.put(objectName, urlCache);
				}
			}
		}
		URL url = urlCacheMap.get(objectName).url;
		String httpUrl = url.toString();
		String httpsUrl = httpUrl.replaceAll("http", "https");
		response.sendRedirect(httpsUrl);
	}
	
}
